import Taro from '@tarojs/taro'
import { View, Text, Form, CheckboxGroup, Checkbox, Radio, RadioGroup, Label, Button, PageContainer } from '@tarojs/components'
import { useEffect, useReducer, useRef, useState } from 'react'
import { AtButton, AtSearchBar, AtDrawer, AtFab } from 'taro-ui'
import './index.scss'
import { hideLoading, reducer, showLoading, showModal } from '../../../utils'
import XCheckbox from '../../../components/XCheckbox'
import XLoadMore from '../../../components/XLoadMore'
import EditPage from './edit'
import PviewPage from './preview'
import { chargeStrategyPaginationApi, deleteChargeStrategy } from '../../../services/ChargeStrategy'

interface StrategyRow extends Strategy {
    checked:boolean
}

export default () => {
    let [state, stateDispatch] = useReducer(reducer, {
        isOpenPageContainer : false,
        pageContainerType : '',
        openShowEdit : false,
        editIng : false,
        isShowFilterAside : false
    })

    let loadMoreRef = useRef<any>(null)
    let [currentStrategy, setcurrentStrategy] = useState<any>(null)
    let [filterParams, filterParamsDispatch] = useState<any>({})

    let [dataList, setdataList] = useState<StrategyRow[]>([])
    let [selectedstrategyIds, setselectedstrategyIds] = useState<(string|number)[]>([])
    let [isAllSelected, setisAllSelected] = useState(false)


    function search() { //搜索
        setdataList([])
        loadMoreRef.current.reLoad()
    }

    function filterFormSubmit(params:any) {
        filterParamsDispatch({...params})
        search()
        stateDispatch({isShowFilterAside : false})
    }

    function toggleOpenEidtPageContainer(strategy?:StrategyRow, index?:number) { //打开保存策略的page-container
        Taro.setNavigationBarTitle({
            title : strategy ? '新增策略' : '编辑策略'
        })
        if(strategy) {
            setcurrentStrategy({...strategy, $index:index})
        }else {
            setcurrentStrategy(null)
        }
        
        stateDispatch({isOpenPageContainer : true, pageContainerType : 'edit'})
    }
    function closePageContainer() { //关闭保存策略page-container触发的
        Taro.setNavigationBarTitle({
            title : '策略列表'
        })
        stateDispatch({isOpenPageContainer : false})
    }
    function finishEditSaveStrategy(strategy:Strategy|null) { //完成保存策略
        if(strategy) {
            if(currentStrategy) { //编辑
                dataList[currentStrategy.$index] = Object.assign(dataList[currentStrategy.$index], strategy)
            }else { //新增
                dataList.unshift({checked : false, ...strategy})
            }

            setdataList([...dataList])
        }
        
        stateDispatch({isOpenPageContainer : false})
    }

    async function deleteRow(id:number | any[], index?:number) { //删除
        showModal({
            content : '确定删除选中的策略吗',
            showCancel : true,
            async success({cancel}) {
                if(cancel) return
                showLoading()
                let res = await deleteChargeStrategy(id)
                if(res) {
                    if(Array.isArray(id)) {
                        dataList = dataList.filter(row => !id.includes(String(row.strategyId)))
                    }else {
                        dataList.splice(index as number, 1)
                    }
                    setdataList([...dataList])
                    toggleAllSelect(0)
                }else {
                    showModal('删除失败')
                }
                hideLoading()
            }
        })
        
    }

    function openDetailPageContainer(strategy:StrategyRow) { //打开查看
        Taro.setNavigationBarTitle({
            title : '策略详情'
        })
        setcurrentStrategy(strategy)
        stateDispatch({isOpenPageContainer : true, pageContainerType : 'detail'})
    }

    function toggleEdit() {
        if(state.editIng == true) {
            changeSelect([])
        }

        stateDispatch({editIng : !state.editIng})
    }

    function toggleAllSelect(count:number) {
        if(count == 0) { //取消全选
            changeSelect([])
        }else { //全选
            changeSelect(dataList.map(item => String(item.strategyId!)))
        }
        
    }

    function changeSelect(values:Array<number|string>) {
        setselectedstrategyIds(values)
        dataList.forEach(item => {
            item.checked = values.includes(String(item.strategyId))
        })
        setdataList([...dataList])
    }

    function loadFinish(rows:Strategy[]) {
        if(rows.length > 0) {
            let newDataList:StrategyRow[] = [...dataList]
            rows.forEach(row => {
                newDataList.push({checked : false, ...row})
            })

            setdataList(newDataList)
        }
    }

    useEffect(() => {
        if(selectedstrategyIds.length > 0 && (selectedstrategyIds.length == dataList.length)) {
            setisAllSelected(true)
        }else {
            setisAllSelected(false)
        }
    }, [selectedstrategyIds])
    
    return <>
        <View className='header'>
            <View className='flex-align-items-center p-r bc-fff'>
                {state.editIng
                ? <>
                    <View className='edit-operate'>
                        <View style='display:inline-block'>
                            <AtButton className='item' size='small' disabled={selectedstrategyIds.length == 0} onClick={() => deleteRow(selectedstrategyIds)}>删除</AtButton>
                        </View>
                        <View style='display:inline-block' className='m-l-20'>
                            <AtButton className='item' size='small' disabled={selectedstrategyIds.length == 0} type='primary'>分配</AtButton>
                        </View>
                        <View style='display:inline-block' className='m-l-20'>
                            <AtButton className='item' size='small' disabled={selectedstrategyIds.length == 0} type='primary'>禁用</AtButton>
                        </View>
                    </View>
                    <View onClick={toggleEdit}>完成</View>
                </>
                : <>
                    <View className='flex-1'>
                        <AtSearchBar disabled={state.editIng} placeholder='策略名' value={filterParams.name} onChange={keyword => {filterParamsDispatch({name : keyword}) }} onConfirm={search} onActionClick={search}></AtSearchBar>
                    </View>
                    <View className='filter-icon' onClick={() => stateDispatch({isShowFilterAside : true})}></View>
                    <View className='edit-icon m-l-20' onClick={toggleEdit}></View>
                </>
                }
            </View>
            {state.editIng &&
                <View className='m-t-30 p-l-r'>
                    <CheckboxGroup onChange={e => toggleAllSelect(e.detail.value.length)}>
                        <XCheckbox checked={isAllSelected} indeterminate={!isAllSelected && selectedstrategyIds.length > 0} value={'1'}>{isAllSelected ? '取消全选' : '全选'}</XCheckbox>
                    </CheckboxGroup>
                </View>
            }
        </View>
        <CheckboxGroup onChange={e => { changeSelect(e.detail.value)  }}>
            {
                dataList.map((item, index) => <View className='row-item'>
                    <View className='flex-1'>
                        <View className='p-l-r'>
                            <View className='f-32'>策略名：<Text user-select>{item.strategyName}</Text></View>
                            <View className='color-999 m-t-10'>
                                {/* <View>设备号：<Text user-select>{item.deviceNo}</Text></View>
                                <View>端口数：10，策略：小学二区充3块3度电</View>
                                <View>连接状态：<Text className='color-f56c6c'>掉线</Text>，心跳时间：<Text>2012-12-12 12:12:12</Text></View> */}
                            </View>
                        </View>
                        <View className='bottom-nav p-l-r'>
                            <AtButton disabled={state.editIng} className='item' size='small' onClick={() => deleteRow(item.strategyId as number, index)}>删除</AtButton>
                            <AtButton disabled={state.editIng} className='item' size='small' onClick={() => openDetailPageContainer(item) }>查 看</AtButton>
                            <AtButton disabled={state.editIng} className='item' size='small' onClick={() => toggleOpenEidtPageContainer(item, index)}>编 辑</AtButton>
                        </View>
                    </View>
                    {state.editIng &&
                        <View className='p-l-r'>
                            <Checkbox checked={item.checked} value={String(item.strategyId)}></Checkbox>
                        </View>
                    }
                </View>)
            }
            
        </CheckboxGroup>

        <View style={'display:' + (state.editIng ? 'none' : 'block')}>
            <XLoadMore ref={loadMoreRef} queryParams={filterParams} onClick={params => chargeStrategyPaginationApi(params)} pageSize={15} onFinish={rows => loadFinish(rows)} keyName='strategyId'></XLoadMore>
        </View>

        <AtDrawer show={state.isShowFilterAside} onClose={() => stateDispatch({isShowFilterAside : false})} right>
            <Form onSubmit={e => filterFormSubmit(e.detail.value)}>
                <View className='p-box'>
                    <View className='f-32'>策略类型</View>
                    <RadioGroup  name='type' className='flex-align-items-center m-t-20'>
                        <Label>
                            <Radio value='' checked={filterParams.type == ''}></Radio>全部
                        </Label>
                        <Label className='m-l-30'>
                            <Radio value='1'></Radio>计时
                        </Label>
                        <Label className='m-l-30'>
                            <Radio value='2'></Radio>计量
                        </Label>
                    </RadioGroup>
                </View>
                <View className='flex-align-items-center m-t-20 p-l-r'>
                    {/* <Button className='flex-1 f-28' formType='reset'>重 置</Button> */}
                    <Button className='flex-1 f-28 primary' formType='submit'>确 定</Button>
                </View>
            </Form>
        </AtDrawer>

        <PageContainer custom-style='z-index:10' show={state.isOpenPageContainer} position='center' onBeforeLeave={closePageContainer}>
            <View className='edit-container'>
                {state.isOpenPageContainer &&
                    <>
                        {state.pageContainerType == 'edit' &&
                            <EditPage strategy={currentStrategy} onFinish={finishEditSaveStrategy}></EditPage>
                        }
                        {state.pageContainerType == 'detail' &&
                            <PviewPage strategy={currentStrategy}></PviewPage>
                        }
                    </>
                }
            </View>
        </PageContainer>

        {!state.editIng &&
            <View className='add-btn' onClick={() => toggleOpenEidtPageContainer()}>
                <AtFab>
                    <Text className='at-icon at-icon-add'></Text>
                </AtFab>
            </View>
        }
    </>
}